package graphics;


import data.*;

import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.util.Timer;
import java.awt.*;
import java.awt.event.*;
import java.util.TimerTask;

/**
 * @author Brett Garcia
 * @version 1.0
 */
public class MULEPanel extends JPanel
{
	private final Map map;
    private boolean landSelected;
    private boolean playerdone;
    int roundCounter;
    Tile currTile;
    Player currPlayer;
	
	public MULEPanel(final Map map)
	{
		setLayout(new BorderLayout());
		setSize(800, 600);
		this.map = map;
        roundCounter = 0;
        currTile = map.getMap()[0][0];
        currPlayer = map.getPlayers()[0];
		setFocusable(true);
		showMap(map.getCurrentPlayer());

        Thread thread = new Thread(){
            public void run(){
                landSelection();
            }
        };
        thread.start();
	}

	private void showMap(final Player myTurn)
	{
		removeAll();
		setLayout(new GridLayout(5, 9));
		Tile[][] tiles = map.getMap();

		for (Tile[] i : tiles)
		{
			for (final Tile j : i)
			{
				JButton button = new JButton(j.getIcon());
                if(j.hasOwner())
                {
                button.setBorder(BorderFactory.createLineBorder(Player.COLORS.get(j.getOwner().getColor()),2));
				button.addActionListener(new ActionListener() {
					@Override
					public void actionPerformed(ActionEvent actionEvent) {
						if (!myTurn.isUser())
						{
							return;
						}
						if (j.isTown())
						{
							enterTown(myTurn);
						}
						else
						{
							if (j.getOwner() == myTurn)
							{
								if (myTurn.hasFreeMule())
								{
									j.placeMule(myTurn.getFreeMule());
								}
								else
								{
									JOptionPane.showMessageDialog(MULEPanel.this,
											"You do not have any M.U.L.E's to put there");
								}
							}
						}
					}
				});
				add(button);
			}
		}
	}
    }

    private void showMap(final Player myTurn, Tile tile)
    {
        removeAll();
        setLayout(new GridLayout(5, 9));
        Tile[][] tiles = map.getMap();

        for (Tile[] i : tiles)
        {
            for (final Tile j : i)
            {
                JButton button = new JButton(j.getIcon());
                if(j.hasOwner()){
                    button.setBorder(BorderFactory.createLineBorder(j.getOwner().getColor(),2));
                }else if(j == tile){
                    button.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
                }
                button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!myTurn.isUser())
                        {
                            return;
                        }
                        if (j.isTown())
                        {
                            enterTown(myTurn);
                        }
                        else
                        {
                            if (j.getOwner() == myTurn)
                            {
                                if (myTurn.hasFreeMule())
                                {
                                    j.placeMule(myTurn.getFreeMule());
                                }
                                else
                                {
                                    JOptionPane.showMessageDialog(MULEPanel.this,
                                            "You do not have any M.U.L.E's to put there");
                                }
                            }
                        }
                    }
                });
                add(button);
            }
        }
    }


	private void enterTown(final Player myTurn)
	{
		//TODO:  add a message saying press escape to go back
		removeAll();
		setLayout(new GridLayout(0, 3));

		JButton storeButton = new JButton(Store.ICON);
		storeButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				enterStore(myTurn);
			}
		});
		add(storeButton);

		JButton pubButton = new JButton(Pub.ICON);
		pubButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				gamble(myTurn);
			}
		});
		add(pubButton);

		JButton landOfficeButton = new JButton(LandOffice.ICON);
		landOfficeButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				enterLandOffice(myTurn);
			}
		});
		add(landOfficeButton);

		addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
				{
					showMap(myTurn);
				}
			}
		});
	}

	private void enterStore(Player myTurn)
	{

	}

	private void gamble(Player myTurn)
	{

	}

	private void enterLandOffice(Player myTurn)
	{

	}

    private void landSelection ()
    {
        Player[] players = map.getPlayers();
        Tile[][] tiles = map.getMap();
        landSelected = true;
        playerdone = false;
        setRoundCounter(0);
        setCurrTile(tiles[0][0]);

        class Selector extends AbstractAction{
            public void actionPerformed(ActionEvent event){

                if(getRoundCounter() >= 2){

                    if(currPlayer.getMoney() >= 200){
                        currPlayer.makePurchase(200);
                        currPlayer.addProperty(getCurrTile());
                        landSelected = true;
                        playerdone = true;
                    }
                }else{
                    currPlayer.addProperty(getCurrTile());
                    landSelected = true;
                    playerdone = true;
                }
                System.out.println("enter is acknowledged");
            }
        }


       getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "select");
       getActionMap().put("select", new Selector());

        while(landSelected){
            landSelected = false;

            for(Player p : players){

                currPlayer = p;
                playerdone = false;

                for (Tile[] i : tiles)
                {
                    for (final Tile j : i)
                    {
                        currTile = j;

                        if(j.getOwner() == null && !j.isTown()){
                            showMap(map.getCurrentPlayer(), j);

                            try{
                                Thread.sleep(2500);
                                System.out.println("moving to next tile" + " " + roundCounter);
                            }catch(InterruptedException e){
                                System.err.println("something went wrong");
                            }

                            if(landSelected && playerdone){
                                break;
                            }
                        }
                    }

                    if(landSelected && playerdone){
                        break;
                    }
                }
            }

            roundCounter++;
        }
        showMap(map.getCurrentPlayer());
    }

    public Tile getCurrTile(){
        return currTile;
    }

    public void setCurrTile(Tile tile){
            currTile = tile;
    }

    public int getRoundCounter(){
        return roundCounter;
    }

    public void setRoundCounter(int i){
        roundCounter = i;
    }
}